package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.Settings;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.model.vo.UserLikeListVo;
import com.tanhua.server.intercepror.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class UsersService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private SettingsApi settingsApi;

    @DubboReference
    private BlackListApi blackListApi;

    //根据id查询用户信息
    public UserInfoVo findUserInfoById(Long userId) {
        //查询数据库中的UserInfo对象
        UserInfo info = userInfoApi.findById(userId);
        //将UserInfo对象转化成UserInfoVo
        UserInfoVo vo = new UserInfoVo();
        //将参数一对象中的同名+同类型属性拷贝到参数二对象中
        BeanUtils.copyProperties(info,vo);
        if(info.getAge() !=null) {  //对其他属性复制
            vo.setAge(info.getAge().toString());
        }
        return vo;
    }

    //更新
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //通用设置
    public SettingsVo settings() {
        //1、创建SettingsVo对象
        SettingsVo vo = new SettingsVo();
        //2、设置手机号码
        Long userId = UserHolder.getUserId();
        String mobile = UserHolder.getMobile();
        vo.setId(userId);
        vo.setPhone(mobile);
        //3、调用API查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        String txt = question == null ? "你喜欢java吗" : question.getTxt();
        vo.setStrangerQuestion(txt);
        //4、调用API查询通知开关
        Settings settings = settingsApi.findByUserId(userId);
        if(settings != null) {
            vo.setGonggaoNotification(settings.getGonggaoNotification());
            vo.setLikeNotification(settings.getLikeNotification());
            vo.setPinglunNotification(settings.getPinglunNotification());
        }else {
            vo.setGonggaoNotification(true);
            vo.setLikeNotification(true);
            vo.setPinglunNotification(true);
        }
        //5、构造返回
        return vo;
    }

    //设置陌生人问题：保存或者更新
    public void questions(String content) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API根据用户id查询陌生人问题
        Question question = questionApi.findByUserId(userId);
        //3、如果对象存在，调用API更新
        if(question!=null) {
            question.setTxt(content);
            questionApi.update(question);
        }else {
            //4、如果不存在，调用API保存
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);

            questionApi.save(question);
        }
    }

    //设置通知开关：保存或更新
    public void setting(Boolean likeNotifi, Boolean pinglunNotifi, Boolean gonggaoNotifi) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API根据用户id查询通知开关
        Settings settings = settingsApi.findByUserId(userId);
        //3、如果对象存在，调用API更新
        if(settings != null) {
            settings.setPinglunNotification(pinglunNotifi);
            settings.setLikeNotification(likeNotifi);
            settings.setGonggaoNotification(gonggaoNotifi);
            settingsApi.update(settings);
        }else {
            //4、如果不存在，调用API保存
            settings = new Settings();
            settings.setUserId(userId);
            settings.setPinglunNotification(pinglunNotifi);
            settings.setLikeNotification(likeNotifi);
            settings.setGonggaoNotification(gonggaoNotifi);
            settingsApi.save(settings);
        }
    }

    //分页查询黑名单数据
    public PageResult blacklist(Integer page, Integer pagesize) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API分页查询黑名单数据，IPage对象
        IPage<UserInfo> iPage = blackListApi.findByUserId(userId,page,pagesize);
        //3、将IPage转化为PageResult
        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }



    //移除黑名单 -- 删除黑名单中的数据
    public void delBlackList(Long blackUserId) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API删除黑名单数据
        blackListApi.delete(userId,blackUserId);
    }


    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * @param integer
     * @param page
     * @param type :查询类型
     *      1 互相关注
     *      2 我关注
     *      3 粉丝
     *            以上三项，实战内容
     */
    public PageResult friends(Integer type, Integer page, Integer pagesize) {


        if(type != 4) {
            //实战独立完成
            return new PageResult();
        }
        //根据用户id，查询访客数据  List<visitors>
        Long userId = UserHolder.getUserId();
        List<Visitors> list = visitorsApi.findAll(userId,page,pagesize);
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //一个visitors转话一个VO
        List<Long> ids = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<UserLikeListVo> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            //访客的用户信息，visitors对象
            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            UserLikeListVo vo = UserLikeListVo.init(userInfo,visitors);
            vos.add(vo);
        }
        //查询访客历史时，记录访问时间
        String key = Constants.VISITORS_USER+UserHolder.getUserId();
        Long time = System.currentTimeMillis();
        redisTemplate.opsForValue().set(key,time.toString());
        //返回
        return new PageResult(page,pagesize,0l,vos);
    }
}
